package com.hbsd.paopaobackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbsd.paopaobackend.common.ErrorCode;
import com.hbsd.paopaobackend.common.request.DeleteRequest;
import com.hbsd.paopaobackend.exception.BusinessException;
import com.hbsd.paopaobackend.mapper.TagMapper;
import com.hbsd.paopaobackend.model.domain.ChildrenTag;
import com.hbsd.paopaobackend.model.domain.Tag;
import com.hbsd.paopaobackend.model.domain.User;
import com.hbsd.paopaobackend.model.request.PageInfo;
import com.hbsd.paopaobackend.model.request.Tag.AddTagRequest;
import com.hbsd.paopaobackend.model.request.Tag.UpdateChildrenTagRequest;
import com.hbsd.paopaobackend.service.TagService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zzh
* @description 针对表【tag(标签表)】的数据库操作Service实现

*/
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
    implements TagService {

    /**
     * 新增标签
     * @param addTagRequest
     * @param loginUser
     * @return
     */
    @Override
    public Boolean addTag(AddTagRequest addTagRequest, User loginUser) {

        if(addTagRequest == null ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }

        String tagName = addTagRequest.getTagName();
        if(tagName == null || tagName.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签名不能为空");
        }

        Integer isParent = addTagRequest.getIsParent();
        if(isParent == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "是否为父标签不能为空");
        }



        // 不是父级标签(子标签)
        if(isParent == 0) {
            Long parentId = addTagRequest.getParentId();
            if(parentId == null || parentId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "父标签id不能为空");
            }
            QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", parentId);
            Tag parentTag = this.getOne(queryWrapper);  // 获取父标签
            if(parentTag == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "父标签不存在");
            }
        } else {
            // 父级标签
            Long parentId = null;
            addTagRequest.setParentId(parentId);
        }

        Long loginUserId = loginUser.getId();
        if(loginUserId <= 0 || loginUserId == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        // 设置用户id
        addTagRequest.setUserId(loginUserId);


        Tag tag = new Tag();
        try {
            BeanUtils.copyProperties(tag, addTagRequest);
        } catch (Exception e) {
          throw new BusinessException(ErrorCode.PARAMS_ERROR, "赋值错误");
        }

        boolean save = this.save(tag);
        if(!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "保存失败");
        }

        return save;


    }

    /**
     * 获取标签列表
     *
     * @param pageInfo
     * @return
     */

    @Override
    public List<Map<String, Object>> GettagList(PageInfo pageInfo) {
        // Step 1: 获取分页信息
        long pageNum = pageInfo.getPageNum();
        long pageSize = pageInfo.getPageSize();
        // Step 2: 构建分页查询条件
        Page<Tag> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        // Step 3: 执行分页查询
        Page<Tag> resultPage = this.page(page, queryWrapper);

        // Step 4: 构建返回结果
        List<Tag> tags = resultPage.getRecords();



        // Step 1: 使用 Map 分类标签，方便查找子标签
        Map<Long, List<Tag>> parentIdToChildrenMap = tags.stream()
                // 过滤掉非父标签
                .filter(tag -> tag.getParentId() != null)
                // 过滤掉父标签
                .collect(Collectors.groupingBy(Tag::getParentId));

        System.out.println("parentIdToChildrenMap = " + parentIdToChildrenMap);

        // 这里会生成这样的数据结构
        //"4": [
        //      {
        //        "id": 5,
        //        "tagName": "男",
        //        "userId": 2,
        //        "parentId": 4,
        //        "isParent": 0,
        //        "createTime": "2024-11-08 17:13:57",
        //        "updateTime": "2024-11-08 17:13:57",
        //        "isDelete": 0,
        //        "remark": ""
        //      },
        //      {
        //        "id": 6,
        //        "tagName": "女",
        //        "userId": 2,
        //        "parentId": 4,
        //        "isParent": 0,
        //        "createTime": "2024-11-08 17:14:01",
        //        "updateTime": "2024-11-08 17:14:01",
        //        "isDelete": 0,
        //        "remark": ""
        //      }
        //    ],


        // Step 2: 获取父标签
        List<Tag> parentTags = tags.stream()
                .filter(tag -> tag.getIsParent() == 1)
                .collect(Collectors.toList());

        //[
        //    {
        //      "id": 4,
        //      "tagName": "性别",
        //      "userId": 2,
        //      "parentId": null,
        //      "isParent": 1,
        //      "createTime": "2024-11-08 17:13:45",
        //      "updateTime": "2024-11-08 17:13:45",
        //      "isDelete": 0,
        //      "remark": ""
        //    },
        //    {
        //      "id": 7,
        //      "tagName": "级别",
        //      "userId": 2,
        //      "parentId": null,
        //      "isParent": 1,
        //      "createTime": "2024-11-08 17:18:06",
        //      "updateTime": "2024-11-08 17:18:06",
        //      "isDelete": 0,
        //      "remark": ""
        //    },
        //]


        // Step 3: 构建父标签与子标签的树形结构
        List<Map<String, Object>> organizedTags = new ArrayList<>();
        for (Tag parentTag : parentTags) {
            Map<String, Object> parentMap = new HashMap<>();
            parentMap.put("id", parentTag.getId());
            parentMap.put("tagName", parentTag.getTagName());

            // 获取当前父标签的子标签
            List<Tag> children = parentIdToChildrenMap.get(parentTag.getId());
            if (children != null) {
                parentMap.put("children", children);
            } else {
                parentMap.put("children", new ArrayList<>());
            }

            organizedTags.add(parentMap);
        }

        return organizedTags;
    }

    /**
     * 批量更新标签
     * @param updateChildrenTagRequests
     * @return
     */
    @Override
    public boolean updateTagsBatch(UpdateChildrenTagRequest[] updateChildrenTagRequests) {
        for (UpdateChildrenTagRequest tag : updateChildrenTagRequests) {
            // 更新当前标签
            if (tag.getId() == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签 ID 不能为空");
            }

            // 将 `UpdateChildrenTagRequest` 转换为 `Tag` 实体类对象，假设此转换通过一个方法完成
            Tag entityTag = convertToEntity(tag);
            boolean updated = updateById(entityTag);
            if (!updated) {
                System.out.println("Failed to update tag with ID: " + tag.getId());
                return false;
            }

            // 如果有子标签，递归更新子标签
            if (tag.getChildren() != null && tag.getChildren().length > 0) {
                boolean childrenUpdated = updateChildrenTags(tag.getChildren());
                if (!childrenUpdated) {
                    return false; // 子标签更新失败，直接返回失败
                }
            }
        }
        return true; // 全部更新成功
    }

    /**
     * 删除标签
     * @param deleteRequest
     * @return
     */
    @Override
    public boolean deleteTag(DeleteRequest deleteRequest) {
        if(deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }

        long id = deleteRequest.getId();
        boolean result = this.removeById(id);
        if(!result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除失败");
        }
        return true;


    }

    /**
     * 批量更新子标签
     * @param childrenTags
     * @return
     */
    public boolean updateChildrenTags(ChildrenTag[] childrenTags) {
        for (ChildrenTag childTag : childrenTags) {
            if (childTag.getId() == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "子标签 ID 不能为空");
            }

            // 将 ChildrenTag 转换为 Tag
            Tag convertedTag = convertChildrenTagToTag(childTag);

            // 更新子标签
            boolean updated = updateById(convertedTag);
            if (!updated) {
                System.out.println("Failed to update child tag with ID: " + childTag.getId());
                return false;
            }
        }
        return true;
    }

    /**
     * 将 ChildrenTag 转换为 Tag
     * @param childTag
     * @return
     */
    private Tag convertChildrenTagToTag(ChildrenTag childTag) {
        Tag tag = new Tag();
        tag.setId(childTag.getId());
        tag.setTagName(childTag.getTagName());
        tag.setUserId(childTag.getUserId());
        tag.setParentId(childTag.getParentId());
        tag.setIsParent(childTag.getIsParent());
        tag.setRemark(childTag.getRemark());
        return tag;
    }

    /**
     * 将 UpdateChildrenTagRequest 转换为 Tag 实体类对象
     * @param request
     * @return
     */
    private Tag convertToEntity(UpdateChildrenTagRequest request) {
        Tag entity = new Tag();
        entity.setId(request.getId());
        entity.setTagName(request.getTagName());
        entity.setUserId(request.getUserId());
        entity.setParentId(request.getParentId());
        entity.setIsParent(request.getIsParent());
        entity.setRemark(request.getRemark());
        return entity;
    }


}




